from flask import current_app, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants
from info.utils.response_code import RET
# from flask import url_for,current_app

# from info import redis_store
from info.models import User, News, Category
from info.modules.index import index_blu


@index_blu.route('/')
def index():
    # redis_store.set('***','itheima')
    # session['name'] = 'dong111'
    # return 'index'
    user_id = session.get("user_id",None)
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as ret:
            current_app.logger.error(ret)
    click_news = []
    try:
        click_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS ).all()
    # 等效click_news = News.query.order_by(News.clicks.desc()).paginate(1, 6).items
    # clicks = [news.to_basic_dict() for news in click_news]
    except Exception as ret:
        current_app.logger.error(ret)

    # 加载首页分类数据
    categories = Category.query.all()
    category_li = [category.to_dict() for category in categories]
    data = {
        "user": user.to_dict() if user else None,
        "clicks_news": click_news,
        "category_li": category_li
        # 等效"clicks_news":  clicks
    }
    return render_template('news/index.html', data=data)


@index_blu.route('/center')
def center():
    return 'center'


@index_blu.route('/favicon.ico')
def favicon():
    return redirect('/static/news/favicon.ico')
    # return current_app.send_static_file('news/favicon.ico')


@index_blu.route('/news_list')
def news_list():
    cid = request.args.get("cid",1)
    page = request.args.get("page",1)
    per_page = request.args.get("per_page",10)
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as ret:
        current_app.logger.debug(ret)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    filters = [News.status == 0]  #审核通过才展示
    if cid != 1:
        filters.append(News.category_id==cid)
        # filters 中保存的News.category_id==cid是一个查询对象
        # print(filters)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    news_model_list = paginate.items  # 模型对象列表
    total_page = paginate.pages
    current_page = paginate.page
    news_dict_list = [news.to_basic_dict() for news in news_model_list]

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_list": news_dict_list
    }
    return jsonify(errno=RET.OK, errmsg="OK",data=data)
